##
## Hosted Game: Deathmatch
## D1st0rt, SSCE Hyperspace
## License: MIT/X11
## Created: 2009-01-15
## Updated: 2009-05-12
##
## Simple deathmatch module that functions as a very basic demo of how
## to make a game run on top of the Hosted Game core
##
import asss

chat = asss.get_interface(asss.I_CHAT)
game = asss.get_interface(asss.I_GAME)
stats = asss.get_interface(asss.I_STATS)
hgcore = asss.get_interface(asss.I_HGCORE)

HGR_KILLS_REACHED = 1

class HG_Deathmatch:
	iid = asss.I_HOSTEDGAME
	kills = 5

	def OnPrepare(self, a, host, params):
		chat.SendArenaMessage(a, "Deathmatch! First team to %d kills wins!" % self.kills)
		a.hg_dm_teams.clear()
		return (1,)

	def OnStart(self, a, host):
		hgcore.EndInterval(a, asss.INTERVAL_RESET)
		game.GivePrize(a, asss.PRIZE_WARP, 1)
		game.ShipReset(a)
		return (1,)

	def OnGameOver(self, a, how):
		if how == asss.HGR_NONE_REMAINING:
			chat.SendArenaMessage(a, "Game cancelled, nobody left.")
		elif how == HGR_KILLS_REACHED:
			mvpkills = 0
			def find_mvp(p):
				if p.arena == a:
					kills = stats.GetStat(p, asss.STAT_KILLS, asss.INTERVAL_RESET)
					if kills > mvpkills:
						mvpkills = kills
						mvp = p.name

			asss.for_each_player(find_mvp(p))
			chat.SendArenaMessage(a, "%s is the MVP with %d kills!" % (mvp, mvpkills))

	def OnCleanup(self, a):
		a.hg_dm_teams.clear()

	def OnTeamCreate(self, a, team):
		a = team.Arena
		a.hg_dm_teams[team.Freq] = 0

	def OnTeamDestroy(self, a, team):
		a = team.Arena
		if team.Freq in a.hg_dm_teams:
			del a.hg_dm_teams[team.Freq]

	def SizeOfTeamData(self):
		return 0

	def TeamInfoString(self, team, str):
		kills = 0
		deaths = 0
		def accumulate(p):
			if p.arena == team.Arena and p.freq == team.Freq:
				kills += stats.GetStat(p, asss.STAT_KILLS, asss.INTERVAL_RESET)
				deaths += stats.GetStat(p, asss.STAT_DEATHS, asss.INTERVAL_RESET)
		asss.for_each_player(accumulate)
		print(str + " Kills: %d Deaths: %d" % (kills, deaths))
		return (str + " Kills: %d Deaths: %d" % (kills, deaths),)

def PlayerKill(a, killer, killed, bty, flags, pts, green):
	a.hg_dm_teams[killer.freq] += 1
	if a.hg_dm_teams[killer.freq] > a.hg_dm_myint.kills:
		chat.SendArenaMessage(a, "Team %d Wins!" % team)
		hgcore.EndGame(a, HGR_KILLS_REACHED)

def mm_attach(a):
	try:
		a.hg_dm_myint = asss.reg_interface(HG_Deathmatch(), a)
		a.hg_dm_cb1 = asss.reg_callback(asss.CB_KILL, PlayerKill, a)
		a.hg_dm_teams = {}
	except:
		mm_detach(a)
		return

	if hgcore.AttachGame(a, asss.I_HOSTEDGAME, "hg_dm") == 0:
		mm_detach(a)
		raise Exception("Could not attach to HGCore")


def mm_detach(a):
	hgcore.DetachGame(a)
	for attr in ['myint', 'cb1', 'teams']:
		try: delattr(a, 'hg_dm_' + attr)
		except: pass
